package celiasoft.itasalib.query.resultparser;

import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import celiasoft.itasalib.query.ResultsMetaInfo;
import celiasoft.itasalib.structures.DataElement;
import celiasoft.itasalib.structures.MyItasaEpisode;
import celiasoft.itasalib.structures.ShowExtraData;

public class QueryMyItasaEpisodesResultParser extends IQueryResultParser {

	@SuppressWarnings("unused")
	private static final String TAG = "itasalib.parser.AllMyItasaEpisodesResultParser";

	public List<DataElement> parse(Document doc, ResultsMetaInfo meta) {

		ArrayList<DataElement> res = new ArrayList<DataElement>();

		NodeList shows = doc.getElementsByTagName("episodes");

		if (shows.getLength() < 1 || !shows.item(0).hasChildNodes()) {
			return res;
		}

		NodeList nodes = shows.item(0).getChildNodes();

		if (nodes.getLength() > 0) {
			for (int i = 0; i < nodes.getLength(); i++) {
				Node n = nodes.item(i);
			
				DataElement el = parseNode(n);
				if (el != null) {
					res.add(el);
				}
			}
		}

		if (res.size() > 0) {
			setMetaData(doc, meta);
		}

		return res;
	}

	private DataElement parseNode(Node n) {

		Element e = (Element) n;
		MyItasaEpisode el = null;

		int id = W3CParsingHandler.parseIntValue(e, "show_id");
		if (id != -1) {
			el = new MyItasaEpisode(id);
			el.setName(DomHandler.getValue(e, "show_name"));
			
			
			ShowExtraData extra = new ShowExtraData();
			extra.setCountry(DomHandler.getValue(e, "country"));
			extra.setNetwork(DomHandler.getValue(e, "network"));
			extra.setRuntime(W3CParsingHandler.parseIntValue(e, "runtime"));
			extra.setAirtime(W3CParsingHandler.parseTime24hValue(e, "airtime"));
			extra.setNextEpNum(W3CParsingHandler.parseEpisodeDataValue(e, "number"));
			extra.setNextEpTitle(DomHandler.getValue(e, "title"));
			extra.setNextEpDate(W3CParsingHandler.parseSimpleDateValue(e, "date"));
			
			el.setExtraShowData(extra);
		}
		
		return el;
	}

}
